/*
 * Copyright (C) 2013 Michael
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

package com.jm.html.xporta;

import com.jm.commons.fio.FileTypeFilter;
import com.jm.commons.ui.UIBounds;
import com.jm.xporta.XPortException;
import com.jm.xporta.XPorta;
import com.jm.xporta.plugin.XPort;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.imageio.ImageIO;
import javax.swing.filechooser.FileFilter;

/**
 *
 * @created July 26, 2013
 * @author Michael L.R. Marques
 */
public class HtmlXPorta extends XPorta implements XPort {
    
    /**
     * 
     * @param results 
     */
    @Override
    public void initialize(ResultSet results) throws XPortException {
        super.initialize(results);
        UIBounds.setBounds(this);
        // Set the icon image
        try {
            setIconImage(ImageIO.read(getClass().getClassLoader().getResource("com/jm/jmsql/icons/xport.png")));
        } catch (IOException ioe) {}
        setVisible(true);
    }
    
    /**
     * 
     * @return 
     */
    @Override
    public String getName() {
        return "Html XPorta";
    }
    
    /**
     * 
     * @return 
     */
    @Override
    public String getDescription() {
        return "Exports database data to a *.html file.";
    }
    
    /**
     * 
     * @return 
     */
    @Override public FileFilter[] getFileFilters() {
        return new FileFilter[] { new FileTypeFilter("html", "HTML File") };
    }
    
    /**
     * 
     */
    @Override
    public void export() throws XPortException {
        // If data is null throw an exception
        if (getData() == null) {
            throw new XPortException("XPort data was not initialized");
        }
        // If the output file does not exist, throw an exception
        if (getOutput() == null) {
            throw new XPortException("Output file was not initialized");
        }
        // Initialize needed variables
        ResultSet results = getData();
        int totalColumns = 0;
        String[] columnNames;
        setProgressMinimum(0);
        setProgressValue(0);
        // Collect the result sets infromation
        try {
            results.last();
            setProgressMaximum(results.getRow());
            ResultSetMetaData meta = results.getMetaData();
            totalColumns = meta.getColumnCount();
            columnNames = new String[totalColumns];
            for (int i = 0; i < totalColumns; i++) {
                columnNames[i] = meta.getColumnName(i+1);
            }
            results.beforeFirst();
        } catch (SQLException sqle) {
            throw new XPortException(sqle.getMessage(), sqle.getCause());
        }
        // Catch IO errors and throw XPortException
        try {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("<html>\n");
            stringBuilder.append("\t<head>\n");
            stringBuilder.append("\t\t<style>\n");
            stringBuilder.append("\t\t\ttable {\n");
            stringBuilder.append("\t\t\t\tborder-collapse:collapse;\n");
            stringBuilder.append("\t\t\t\tfont: \"Times New Roman\", Times, serif;\n");
            stringBuilder.append("\t\t\t}\n");
            stringBuilder.append("\t\t\tth {\n");
            stringBuilder.append("\t\t\t\tfont-size: 17px;\n");
            stringBuilder.append("\t\t\t\tpadding: 2px 4px 2px 4px;\n");
            stringBuilder.append("\t\t\t\tbackground-color: #4668A6;\n");
            stringBuilder.append("\t\t\t}\n");
            stringBuilder.append("\t\t\ttd {\n");
            stringBuilder.append("\t\t\t\tfont-size: 13px;\n");
            stringBuilder.append("\t\t\t\ttext-align: center;\n");
            stringBuilder.append("\t\t\t}\n");
            stringBuilder.append("\t\t\ttr:nth-child(even) {\n");
            stringBuilder.append("\t\t\t\tbackground-color: #E6E6E6;\n");
            stringBuilder.append("\t\t\t}\n");
            stringBuilder.append("\t\t\ttr:nth-child(odd) {\n");
            stringBuilder.append("\t\t\t\tbackground-color: #FFFFFF;\n");
            stringBuilder.append("\t\t\t}\n");
 
            stringBuilder.append("\t\t\t</style>\n");
            stringBuilder.append("\t\t\t<title>");
            stringBuilder.append(((File) getOutput()).getName());
            stringBuilder.append("</title>\n");
            stringBuilder.append("\t</head>\n");
            stringBuilder.append("\t<body>\n");
            stringBuilder.append("\t\t<div id=\"container\">\n");
            stringBuilder.append("\t\t\t<div id=\"content\">\n");
            stringBuilder.append("\t\t\t\t<table >\n");
            stringBuilder.append("\t\t\t\t\t<tr>\n");
            // Write the header
            for (String column : columnNames) {
                stringBuilder.append("\t\t\t\t\t\t<th>");
                stringBuilder.append(column);
                stringBuilder.append("</th>\n");
           }
            stringBuilder.append("\t\t\t\t\t</tr>\n");
            // Start writting the data to the sheet
            try {
                while(results.next()) {
                    stringBuilder.append("\t\t\t\t\t<tr>\n");
                    for (int column = 1; column <= totalColumns; column++) {
                        stringBuilder.append("\t\t\t\t\t\t<td>");
                        Object object = results.getObject(column);
                        stringBuilder.append(object != null ? object.toString() : "");
                        stringBuilder.append("</td>\n");
                    }
                    stringBuilder.append("\t\t\t\t\t</tr>\n");
                    setProgressValue(getProgressValue() + 1);
                }
            } catch (SQLException sqle) {
                throw new XPortException(sqle.getMessage(), sqle.getCause());
            }
            stringBuilder.append("\t\t\t\t</table>\n");
            stringBuilder.append("\t\t\t</div>\n");
            stringBuilder.append("\t\t\t<div id=\"footer\">\n");
            stringBuilder.append("\t\t\t\t<hr style=\"height: 1px;\"/>\n");
            stringBuilder.append("\t\t\t\t<p>Copyright &copy;2010 - 2013, JMSql.</p>\n");
            stringBuilder.append("\t\t\t</div>\n");
            stringBuilder.append("\t\t</div>\n");
            stringBuilder.append("\t</body>\n");
            stringBuilder.append("</html>\n");
            try (FileWriter writer = new FileWriter((File) getOutput())) {
                writer.write(stringBuilder.toString());
            }
        } catch (IOException ioe) {
            throw new XPortException(ioe.getMessage(), ioe.getCause());
        }
    }

}
